package finelProject.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.dbcp.dbcp.BasicDataSource;

import finelProject.MyAppConstants;

/**
 * Servlet implementation class CheckSessionUserName
 */
public class CheckSessionUserName extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CheckSessionUserName() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Context context;
		try {
			context = new InitialContext();
			PrintWriter out = response.getWriter();
			BasicDataSource ds = (BasicDataSource)context.lookup(MyAppConstants.DB_DATASOURCE);
			Connection conn = ds.getConnection();
			
			String UserName 		= (String) request.getSession().getAttribute("Username");
			
			if(UserName == null){
				response.setIntHeader("success", 0);
			}else{
				try {
					//searching for the user name in the DB
					PreparedStatement stmt;
					stmt = conn.prepareStatement(MyAppConstants.GET_USER);
					stmt.setString	 (1, UserName);
				
					//return users instances of the users who the current user follow.
					ResultSet rs = stmt.executeQuery();
					if(rs.next()){
						out.print("Success");
						response.setIntHeader("success", 1);
					}else{
						response.setIntHeader("success", 0);
					}
					rs.close();
					stmt.close();
					
				} catch (SQLException e) {
					getServletContext().log("Error while querying for customers", e);
		    		response.sendError(500);//internal server error
				}
				conn.close();
				
			}
		}catch(SQLException | NamingException e){
			getServletContext().log("Error while closing connection", e);
    		response.sendError(500);//internal server error
    		
		}
		
	}

}
